package cn.itcast.service.system.impl;

import cn.itcast.dao.system.UserDao;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public PageInfo<User> findByPage(Integer pageNum, Integer pageSize,String companyId) {
        PageHelper.startPage(pageNum,pageSize);
        List<User> list = userDao.findAll(companyId);
        PageInfo<User> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    //查询企业的所有用户
    @Override
    public List<User> findAll(String companyId) {
        List<User> list = userDao.findAll(companyId);
        return list;
    }

    @Override
    public void save(User user) {
        user.setId(UUID.randomUUID().toString());
        /*添加用户或者修改用户密码时，将密码进行md5加盐加密*/
        Md5Hash md5Hash = new Md5Hash(user.getPassword(), user.getEmail());
        user.setPassword(md5Hash.toString());

        userDao.save(user);
    }

    @Override
    public void update(User user) {
        /*添加用户或者修改用户密码时，将密码进行md5加盐加密*/
        Md5Hash md5Hash = new Md5Hash(user.getPassword(), user.getEmail());
        user.setPassword(md5Hash.toString());

        userDao.update(user);
    }

    @Override
    public User findById(String id) {
        User user = userDao.findById(id);
        return user;
    }

    @Override
    public Boolean delete(String id) {
        long count = userDao.findByRoleUserId(id);

        if (count>0){
            return false;
        }

        userDao.delete(id);
        return true;
    }

    //更新用户角色
    @Override
    public void changeRole(String userid, String[] roleIds) {
        userDao.deleteUserRoleByUserId(userid);
        userDao.addUserRole(userid,roleIds);
    }

    //通过email查找用户
    @Override
    public User findByEmail(String email) {
        return userDao.findByEmail(email);
    }
}
